package com.szyjjk.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.szyjjk.entity.*;
import com.szyjjk.imageCrawler.CrawlerTool;
import com.szyjjk.service.RunPropertyServices;
import com.szyjjk.service.RunSiteService;
import com.szyjjk.service.SysHearWordService;
import com.szyjjk.util.DateUtil;
import com.szyjjk.util.FileUtil;
import com.szyjjk.util.HttpTool;
import com.szyjjk.util.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

/**
 * @program: szyjjk
 * @description: 硬件接入数据接口
 * @author: yangyue
 * @create: 2020-05-19 11:46
 */
@Controller
@RequestMapping("/hardware")
public class HardwareInterfaceController {

	@Value("${uploadpath}")
	private String uploadpath;

    @Autowired
    private SysHearWordService sysHearWordService;
//    @Autowired
//	private Sysh

    @Autowired
    private RunPropertyServices runPropertyServices;

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
	@Autowired
	private RunSiteService runSiteService;

    public static Map<String, ScheduledFuture<?>> taskmap = Maps.newHashMap();



	@RequestMapping(value = "/getmoxingdata", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public List<SysHardWareSimulationData> getmoxingdata( Integer id, String modelName){
		List<SysHardWareSimulationData> list =sysHearWordService.getmoxingdata(id,modelName);
		return list;
	}
	@RequestMapping(value = "/gettongji", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public List<Object> gettongji( Integer id){
		List<Object> list =sysHearWordService.gettongji(id);

		return list;
	}
    /**
     * @return com.alibaba.fastjson.JSONObject
     * @Author yangyue
     * @Description //TODO 修改updata
     * @Date 11:31 2020/9/27
     * @Param [runHisData]
     **/
    @RequestMapping(value = "/updataHardWare.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject updataHardWare(String id, String value) {
        JSONObject result = new JSONObject();
        SysHardWareData runHisData1 = this.sysHearWordService.findById(id);
        runHisData1.setDataRemark(value);
        this.sysHearWordService.editSysHardWareData(runHisData1);
        result.put("code", "1");
        return result;
    }


//    @RequestMapping(value = "/HardwareThead.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
//    @ResponseBody
//    public String HardwareThead(HttpServletRequest request, String type) {
//        beginDownLoad();
//        return "";
//    }


    @RequestMapping(value = "/beginDownLoad.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject beginDownLoad() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        List<SysHardWare> sysHardWaresAll = sysHearWordService.findHareWareAll();
        for (SysHardWare sysHardWare : sysHardWaresAll) {
            if (sysHardWare.getWareState() == 1) {
                System.out.println("启动:" + sysHardWare.getWareName());
                //首先进行查询
                //首先获取访问链接的数据
                //进行base64
                String nameAndPassWord = sysHardWare.getWareUsername() + ":" + sysHardWare.getWarePassword(); //格式为  Name:word
                String encoded = Base64.getEncoder().encodeToString(nameAndPassWord.getBytes());
                Map<String, String> head = new HashMap<>();
                head.put("Authorization", "Basic " + encoded);
                String htmlMessage = "";
                try {
                    htmlMessage = CrawlerTool.doGetOnther(sysHardWare.getWareUrl(), head);
                    System.out.println(htmlMessage);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (StringUtils.isNotEmpty(htmlMessage)) {
                    //对html进行解析
                    String Html[] = htmlMessage.split("<pre>");
                    String pre = Html[1].substring(0, Html[1].length() - 28);
                    String[] br = pre.split("<br>");
                    for (int i = 0; i < br.length; i++) {
                        SysHardWareFile sysHardWareFile = new SysHardWareFile();
                        String subTime[] = br[i].split("    ");
                        String dateDay = subTime[0].trim();
                        String time = subTime[1].trim();
                        String sizename = "";
                        if (subTime.length == 4) {
                            sizename = subTime[3];
                        } else {
                            sizename = subTime[2];
                        }
                        String[] sizeUrl = sizename.split("<A");
                        String size = sizeUrl[0].trim();
                        String[] nameAarry = sizeUrl[1].split(">");
                        String name = nameAarry[1].substring(0, nameAarry[1].length() - 3);
                        System.out.println(dateDay + " " + time + " " + size + " " + name);
                        Date downTime = null;
                        try {
                            downTime = HttpTool.HardimpDate.parse(dateDay + " " + time);
                            System.err.println(DateUtil.dateToString2(downTime));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        sysHardWareFile.setFileName(name);
                        sysHardWareFile.setFileUploadTime(downTime);
                        //获取到对应的数据，开始进行查询数据库有没有进行下载
                        List<SysHardWareFile> sysHardWareFileList = this.sysHearWordService.findFileHardByTimeName(name, downTime);
                        if (sysHardWareFileList.size() == 0) {
                            DownLoadHardWare(sysHardWare, sysHardWareFile);
                        }
                    }
                }
            }
        }


        this.disposeHardWareData();
        return jsonObject;
    }

    /**
     * @return void
     * @Author yangyue
     * @Description //TODO 下载接口处的dat数据
     * @Date 14:11 2020/5/20
     * @Param [sysHardWare, sysHardWareFile]
     **/
    public void DownLoadHardWare(SysHardWare sysHardWare, SysHardWareFile sysHardWareFile) {
        //开始下载数据
        //首先创建文件夹
        String filesTime = HttpTool.FilesDate.format(sysHardWareFile.getFileUploadTime());
        File file = new File(sysHardWare.getWarePath() + "\\" + filesTime);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {//如果文件夹不存在
            file.mkdir();//创建文件夹
        }
        //在判断文件春不存在
        File fileR = new File(sysHardWare.getWarePath() + "\\" + filesTime + "\\" + sysHardWareFile.getFileName());
        if (fileR.exists()) {//如果文件存在
            return;
        }
        //开始下载数据
        //首先编辑下载命令
        String wgetExe = CrawlerTool.backWgetPath("WgetPath");
        String downCode = "cmd /c start  " + wgetExe + "       " + sysHardWare.getWareUrl() + sysHardWareFile.getFileName() + "  --http-user=" + sysHardWare.getWareUsername() + "    --http-password=" + sysHardWare.getWarePassword() + "  -O   " + sysHardWare.getWarePath() + "\\" + filesTime + "\\" + sysHardWareFile.getFileName();
        long fileSize = CrawlerTool.wgetDownLoad(downCode, sysHardWare.getWarePath() + "\\" + filesTime, sysHardWareFile.getFileName());
        if (fileSize == 0) {
            return;
        }
        sysHardWareFile.setFileSize(fileSize + "");
        sysHardWareFile.setId(CrawlerTool.getRandomChar(32));
        sysHardWareFile.setFileDownloadTime(new Date());
        sysHardWareFile.setHardId(sysHardWare.getId());
        sysHardWareFile.setFilePath(sysHardWare.getWarePath() + "\\" + filesTime + "\\" + sysHardWareFile.getFileName());
        this.sysHearWordService.saveSysHardWareFile(sysHardWareFile);
    }


    /**
     * @return void
     * @Author yangyue
     * @Description //TODO 处理数据  可以并在下载后执行也可以单独执行
     * @Date 14:16 2020/5/20
     * @Param []
     **/
    @RequestMapping(value = "/disposeHardWareData.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public void disposeHardWareData() {
        List<SysHardWare> sysHardWaresAll = sysHearWordService.findHareWareAll();
        for (SysHardWare sysHardWare : sysHardWaresAll) {
            //首先获得最新要处理的数据
            String dataArray[] = sysHardWare.getWareData().split(";");
            for (int i = 0; i < dataArray.length; i++) {
                //通过要处理的数据去查询最新的数据
                List<SysHardWareFile> sysHardWareFilesList = this.sysHearWordService.findFileHardByName(dataArray[i]);
                if (sysHardWareFilesList.size() > 0) {
                    //在选取最新的数据 如果是SZWUchem_uchem.dat 数据的处理方式 修改 SZWUchem_uchem.dat-NKD_uchem.dat
                    if (dataArray[i].equals("NKD_uchem.dat")) {
                       // NKD_uchem(dataArray, i, sysHardWareFilesList);
                    }else if(dataArray[i].equals("NKD_CSI.dat")){
                    	//NKD_CSI
                    	//NKD_CSI(dataArray, i, sysHardWareFilesList);
                    }else if(dataArray[i].equals("NKD_SONDE.dat")) {
                    	NKD_SONDE(dataArray, i, sysHardWareFilesList);
                    }else if(dataArray[i].equals("NKD_Met.dat")) {
                    	NKD_Met(dataArray, i, sysHardWareFilesList);
                    }
                }
            }
        }
    }


	private void NKD_Met(String[] dataArray, int i, List<SysHardWareFile> sysHardWareFilesList) {


		String dataPath = sysHardWareFilesList.get(0).getFilePath();
		ArrayList<String> arrayList = new ArrayList<>();
		try {
		    FileReader fr = new FileReader(dataPath);
		    BufferedReader bf = new BufferedReader(fr);
		    String str;
		    // 按行读取字符串
		    while ((str = bf.readLine()) != null) {
		        arrayList.add(str);
		    }
		    bf.close();
		    fr.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}

		int length = arrayList.size();
		//必须是14 不然数据对不上

		for (int ind = 4; ind < length; ind++) {
		    String str = arrayList.get(ind);
		    //开始处理数据
		    String[] spielDate = str.split(",");
		    if (spielDate.length == 14) {
		        //时间  再进行转化
		        String timeString = spielDate[0].substring(1, spielDate[0].length() - 1);
		        Date dataTime = null;
		        try {
		            dataTime = HttpTool.longSimpDate.parse(timeString);
		        } catch (ParseException e) {
		            e.printStackTrace();
		            continue;
		        }
		        //先要进行查询，以防插入重复数据
		        if (!this.sysHearWordService.existsHardWareData(dataArray[i], dataTime)) {
		            //直接点，存入数据库
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[1], "数据记录数", "RECORD", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[2], "平均风速", "WSavg", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[3], "最大风速", "WSmax", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[4], "平均风向", "WDavg", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[5], "最大风向", "WDmax", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[6], "空气温度", "AirTC", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[7], "相对湿度", "RH", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[9], "气压", "Pressure", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[10], "雨量", "Rain_mm", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[11], "太阳辐射", "SolarRadiation", dataArray[i]);     
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[12], "光照时长", "sunshineHours", dataArray[i]);     
		        }
		    }
		}
	
		
	
		
	}


	private void NKD_SONDE(String[] dataArray, int i, List<SysHardWareFile> sysHardWareFilesList) {

		String dataPath = sysHardWareFilesList.get(0).getFilePath();
		ArrayList<String> arrayList = new ArrayList<>();
		try {
		    FileReader fr = new FileReader(dataPath);
		    BufferedReader bf = new BufferedReader(fr);
		    String str;
		    // 按行读取字符串
		    while ((str = bf.readLine()) != null) {
		        arrayList.add(str);
		    }
		    bf.close();
		    fr.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}

		int length = arrayList.size();
		//必须是14 不然数据对不上

		for (int ind = 4; ind < length; ind++) {
		    String str = arrayList.get(ind);
		    //开始处理数据
		    String[] spielDate = str.split(",");
		    if (spielDate.length == 17) {
		        //时间  再进行转化
		        String timeString = spielDate[0].substring(1, spielDate[0].length() - 1);
		        Date dataTime = null;
		        try {
		            dataTime = HttpTool.longSimpDate.parse(timeString);
		        } catch (ParseException e) {
		            e.printStackTrace();
		            continue;
		        }
		        //先要进行查询，以防插入重复数据
		        if (!this.sysHearWordService.existsHardWareData(dataArray[i], dataTime)) {
		            //直接点，存入数据库
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[1], "数据记录数", "RECORD", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[2], "水温", "Temp_C", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[4], "电导率", "Cond_mS", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[5], "溶解性固体", "TDS_ppt", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[6], "盐度", "Sal", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[7], "酸碱度", "pH", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[9], "氧化还原电位", "ORP_mV", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[10], "浊度", "Turb_NTU", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[11], "叶绿素", "Chl_ppb", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[13], "溶解氧饱和度", "DO_percent", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[14], "溶解氧", "DO_ppm", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[16], "蓝绿藻", "PE_uL", dataArray[i]);
		        }
		    }
		}
	
		
	}


	private void NKD_CSI(String[] dataArray, int i, List<SysHardWareFile> sysHardWareFilesList) {

		String dataPath = sysHardWareFilesList.get(0).getFilePath();
		ArrayList<String> arrayList = new ArrayList<>();
		try {
		    FileReader fr = new FileReader(dataPath);
		    BufferedReader bf = new BufferedReader(fr);
		    String str;
		    // 按行读取字符串
		    while ((str = bf.readLine()) != null) {
		        arrayList.add(str);
		    }
		    bf.close();
		    fr.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}

		int length = arrayList.size();
		//必须是14 不然数据对不上

		for (int ind = 4; ind < length; ind++) {
		    String str = arrayList.get(ind);
		    //开始处理数据
		    String[] spielDate = str.split(",");
		    System.err.println(Arrays.toString(spielDate));
		    if (spielDate.length == 7) {
		        //时间  再进行转化
		        String timeString = spielDate[0].substring(1, spielDate[0].length() - 1);
		        Date dataTime = null;
		        try {
		            dataTime = HttpTool.longSimpDate.parse(timeString);
		        } catch (ParseException e) {
		            e.printStackTrace();
		            continue;
		        }
		        //先要进行查询，以防插入重复数据
		        if (!this.sysHearWordService.existsHardWareData(dataArray[i], dataTime)) {
		            //直接点，存入数据库
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[1], "数据记录数", "RECORD", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[2], "电子仓湿度", "RH_Enc", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[3], "电子仓温度", "Temp_Enc", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[4], "电池电压", "Batt_Volt", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[5], "纬度", "latitude", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[6], "经度", "longitude", dataArray[i]);
		        }
		    }
		}
	
		
	}


	private void NKD_uchem(String[] dataArray, int i, List<SysHardWareFile> sysHardWareFilesList) {
		String dataPath = sysHardWareFilesList.get(0).getFilePath();
		ArrayList<String> arrayList = new ArrayList<>();
		try {
		    FileReader fr = new FileReader(dataPath);
		    BufferedReader bf = new BufferedReader(fr);
		    String str;
		    // 按行读取字符串
		    while ((str = bf.readLine()) != null) {
		        arrayList.add(str);
		    }
		    bf.close();
		    fr.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}

		int length = arrayList.size();
		//必须是14 不然数据对不上

		for (int ind = 4; ind < length; ind++) {
		    String str = arrayList.get(ind);
		    //开始处理数据
		    String[] spielDate = str.split(",");
		    if (spielDate.length == 14) {
		        //时间  再进行转化
		        String timeString = spielDate[0].substring(1, spielDate[0].length() - 1);
		        Date dataTime = null;
		        try {
		            dataTime = HttpTool.longSimpDate.parse(timeString);
		        } catch (ParseException e) {
		            e.printStackTrace();
		            continue;
		        }
		        //先要进行查询，以防插入重复数据
		        if (!this.sysHearWordService.existsHardWareData(dataArray[i], dataTime)) {
		            //直接点，存入数据库
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[1], "数据记录数", "RECORD", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[2], "氨氮浓度", "NH3_ppm", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[3], "氨氮开始吸光度", "NH3_ODS", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[4], "氨氮吸光度", "NH3_OD", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[5], "氨氮结束吸光度", "NH3_ODE", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[6], "总氮浓度", "TN_ppm", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[7], "总氮开始吸光度", "TN_ODS", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[8], "总氮吸光度", "TN_OD", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[9], "总氮结束吸光度", "TN_ODE", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[10], "总磷浓度", "TP_ppm", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[11], "总磷开始吸光度", "TP_ODS", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[12], "总磷吸光度", "TP_OD", dataArray[i]);
		            this.sysHearWordService.saveSysHardWareDate(dataTime, spielDate[13], "总磷结束吸光度", "TP_ODE", dataArray[i]);
		        }
		    }
		}
	}

    @RequestMapping(value = "/getOptionHarword.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject getOptionHarword(String type) {
        JSONObject jsonObject = new JSONObject();
        if (type.equals("SZWUchem_uchem.dat")) {
            List<String> result = new ArrayList<>();
            result.add("氨氮浓度(NH3_ppm)");
            result.add("氨氮开始吸光度(NH3_ODS)");
            result.add("氨氮吸光度(NH3_OD)");
            result.add("氨氮结束吸光度(NH3_ODE)");
            result.add("总氮浓度(TN_ppm)");
            result.add("总氮开始吸光度(TN_ODS)");
            result.add("总氮吸光度(TN_OD)");
            result.add("总氮结束吸光度(TN_ODE)");
            result.add("总磷浓度(TP_ppm)");
            result.add("总磷开始吸光度(TP_ODS)");
            result.add("总磷吸光度(TP_OD)");
            result.add("总磷结束吸光度(TP_ODE)");
            jsonObject.put("data", result);
        }
        return jsonObject;
    }


    /**
     * @return java.util.List<com.szyjjk.entity.SysHardWareData>
     * @Author yangyue
     * @Description //TODO 得到硬件值
     * @Date 16:18 2020/10/10
     * @Param [pre, begDate, endDate]
     **/
    @RequestMapping(value = "/getHarewaredData.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<SysHardWareData> getHarewaredData(String site,String pre, String begDate, String endDate, String languageType) throws ParseException {
        
    	RunProperty findByProName = runPropertyServices.findByProName1(pre);
    	String y="";
    	if(findByProName!=null) {
    		String proUnit = findByProName.getProUnit();
    		if(StringUtils.isNotBlank(proUnit)) {
    			y=proUnit;
    		}
    	}
    	pre = pre.split("\\(")[0];
        RunProperty runProperty = this.runPropertyServices.findByIDPro(pre);
        if (runProperty != null) {
            pre = UUIDUtils.gethardWareData(runProperty.getProNamech());
        }
//        Date[] timeArray = DateUtil.StringToDate5(begDate, endDate);
//        Date begintime = timeArray[0];
//        Date endtime = timeArray[1];
        // 解析字符串为Date对象
		Date begintime = null;Date endtime = null;
		if (StringUtils.isNoneBlank(begDate) && !begDate.equals("null"))
		begintime = dataToString(begDate);
		if (StringUtils.isNoneBlank(begDate) && !endDate.equals("null"))
			endtime = dataToString(endDate);
        String[] sitearr = null;
        if (StringUtils.isNoneBlank(site)) {
			sitearr = site.split(",");
			sitearr = Arrays.stream(sitearr).filter(s -> !s.isEmpty()).toArray(String[]::new);
		}
        List<SysHardWareData> reulst = this.sysHearWordService.findSysHarwareDateByNameBeginTime(sitearr,pre,begintime, endtime);
        //获取点位
		List<RunSite> allSite = runSiteService.findAllSite();
		Map<String,String> sitemap = allSite.stream().collect(Collectors.toMap(RunSite::getId,RunSite::getSiteName));
//        List<SysHardWareData> reulst = this.sysHearWordService.findSysHarwareDateByBeginTime(begintime, endtime);
        for (SysHardWareData sysHardWareData : reulst) {
        	sysHardWareData.setDanweiy(y);
        	sysHardWareData.setSitename(sitemap.get(sysHardWareData.getDataRemark()));
            if ("zh".equals(languageType)) {
            	if (StringUtils.isNoneBlank(sysHardWareData.getDataNameEn()))
                sysHardWareData.setDataNameEn(sysHardWareData.getDataNameCh() + "(" + sysHardWareData.getDataNameEn() + ")");
            	else
					sysHardWareData.setDataNameEn(sysHardWareData.getDataNameCh());
            }
        }
        return reulst;
    }
    @RequestMapping(value = "/getHarewaredDatabysitename.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<SysHardWareData> getHarewaredDatabysitename(String sitename) throws ParseException {

        List<SysHardWareData> reulst = this.sysHearWordService.findSysHarwareDateBysitename(sitename);
        //获取点位
		List<RunSite> allSite = runSiteService.findAllSite();
		Map<String,String> sitemap = allSite.stream().collect(Collectors.toMap(RunSite::getId,RunSite::getSiteName));
        for (SysHardWareData sysHardWareData : reulst) {
        	sysHardWareData.setSitename(sitemap.get(sysHardWareData.getDataRemark()));
            	if (StringUtils.isNoneBlank(sysHardWareData.getDataNameEn()))
                sysHardWareData.setDataNameEn(sysHardWareData.getDataNameCh() + "(" + sysHardWareData.getDataNameEn() + ")");
            	else
					sysHardWareData.setDataNameEn(sysHardWareData.getDataNameCh());
        }
        return reulst;
    }

    @RequestMapping(value = "/getHarewaredsimulationData.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<SysHardWareSimulationData> getHarewaredsimulationData(String site,String pre, String begDate, String endDate, String languageType) throws ParseException {

    	RunProperty findByProName = runPropertyServices.findByProName1(pre);
    	String y="";
    	if(findByProName!=null) {
    		String proUnit = findByProName.getProUnit();
    		if(StringUtils.isNotBlank(proUnit)) {
    			y=proUnit;
    		}
    	}
    	pre = pre.split("\\(")[0];
        RunProperty runProperty = this.runPropertyServices.findByIDPro(pre);
        if (runProperty != null) {
            pre = UUIDUtils.gethardWareData(runProperty.getProNamech());
        }

        // 解析字符串为Date对象
		Date begintime = null;Date endtime = null;
		if (StringUtils.isNoneBlank(begDate) && !begDate.equals("null"))
		begintime = dataToString(begDate);
		if (StringUtils.isNoneBlank(begDate) && !endDate.equals("null"))
			endtime = dataToString(endDate);
        String[] sitearr = null;
        if (StringUtils.isNoneBlank(site)) {
			sitearr = site.split(",");
			sitearr = Arrays.stream(sitearr).filter(s -> !s.isEmpty()).toArray(String[]::new);
		}
        List<SysHardWareSimulationData> reulst = this.sysHearWordService.findSysHarwaresimulationDateByNameBeginTime(sitearr,pre,begintime, endtime);
        //获取点位
		List<RunSite> allSite = runSiteService.findAllSite();
		Map<String,String> sitemap = allSite.stream().collect(Collectors.toMap(RunSite::getId,RunSite::getSiteName));
        for (SysHardWareSimulationData sysHardWareSimulationData : reulst) {
        	sysHardWareSimulationData.setDanweiy(y);
        	sysHardWareSimulationData.setSitename(sitemap.get(sysHardWareSimulationData.getDataRemark()));
            if ("zh".equals(languageType)) {
            	if (StringUtils.isNoneBlank(sysHardWareSimulationData.getDataNameEn()))
                sysHardWareSimulationData.setDataNameEn(sysHardWareSimulationData.getDataNameCh() + "(" + sysHardWareSimulationData.getDataNameEn() + ")");
            	else
					sysHardWareSimulationData.setDataNameEn(sysHardWareSimulationData.getDataNameCh());
            }
        }
        return reulst;
    }
    public static Date dataToString(String dateString) {


        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
        Date dd = null; //将字符串改为date的格式
        try {
            dd = sdf.parse(dateString);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String resDate= s.format(dd);
        System.out.println(resDate);
        Date result = null;
        try {
            result = s.parse(resDate);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
return result;
    }



    /**
     * @return java.util.List<com.szyjjk.entity.SysHardWare>
     * @Author yangyue
     * @Description //TODO 查询全部
     * @Date 11:40 2020/5/28
     * @Param []
     **/
    @RequestMapping(value = "/getHarewaredAll.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<SysHardWare> getHarewaredAll() {
        return this.sysHearWordService.findHareWareAll();
    }

	/**
	 * 上传
	 */
	@RequestMapping("/upload.do")
	@ResponseBody
	public ResponseBo upload(HttpServletRequest request) {
		ResponseBo rb = new ResponseBo();
		MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
		MultipartFile multipartFile = params.getFile("fileUpload");
		if (!multipartFile.isEmpty()) {
			String fileDownLoadPath = uploadpath;
			String fileName = multipartFile.getOriginalFilename();
			long size = multipartFile.getSize();
			long max = 10L * 1024l * 1024l;
			if (size > max) {
				rb.setCode(0);
				rb.setMessage("上传文件大小超过10M");
				return rb;
			}
			System.out.println("上传文件位置" + fileDownLoadPath);

			try {
				String finalpath = FileUtil.fileUpload(multipartFile, fileDownLoadPath);
				rb.setPath(multipartFile.getOriginalFilename());

				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				ArrayList<SysHardWareData> insertlist = new ArrayList<>();
				//同步到数据库
				if (!fileName.contains("xlsx")){
					HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(finalpath));
					HSSFSheet sheet = workbook.getSheetAt(0);
					for (int i = 0; i < sheet.getLastRowNum(); i++) {
						if (i > 2) {
							Row row = sheet.getRow(i);
							Cell cell = row.getCell(0);
							Date date = sf.parse(cell.getStringCellValue());
							//除时间项
							for (int j = 1; j < row.getLastCellNum(); j++) {

								row.getCell(j).setCellType(CellType.STRING);
								SysHardWareData sysHardWareData = new SysHardWareData();
								sysHardWareData.setDataTime(date);
								sysHardWareData.setDataNameCh(sheet.getRow(1).getCell(j).getStringCellValue());
								sysHardWareData.setDataValue(row.getCell(j).getStringCellValue());
								sysHardWareData.setDataFileName(multipartFile.getOriginalFilename());
								sysHardWareData.setId(UUIDUtils.getUUID());
//								sysHearWordService.saveSysHardWareDate(sysHardWareData);
								insertlist.add(sysHardWareData);
							}
						}

					}
				}else {
					XSSFWorkbook workbook = new XSSFWorkbook(finalpath);
					XSSFSheet sheet = workbook.getSheetAt(0);
					for (int i = 0; i < sheet.getLastRowNum(); i++) {
						if (i > 2) {
							Row row = sheet.getRow(i);
							Cell cell = row.getCell(0);
							Date date = sf.parse(cell.getStringCellValue());
							//除时间项
							for (int j = 1; j < row.getLastCellNum(); j++) {
								SysHardWareData sysHardWareData = new SysHardWareData();
								sysHardWareData.setDataTime(date);
								sysHardWareData.setDataNameCh(sheet.getRow(1).getCell(j).getStringCellValue());
								sysHardWareData.setDataValue(row.getCell(j).getStringCellValue());
								sysHardWareData.setDataFileName(multipartFile.getOriginalFilename());
								sysHardWareData.setId(UUIDUtils.getUUID());
//								sysHearWordService.saveSysHardWareDate(sysHardWareData);
								insertlist.add(sysHardWareData);
							}
						}

					}
				}
				sysHearWordService.saveSysHardWareDate(insertlist);
			} catch (Exception e) {
				e.printStackTrace();
				rb.setCode(0);
				rb.setMessage("上传文件失败");
				return rb;
			}
		} else {
			rb.setCode(0);
			rb.setMessage("上传文件空");
			return rb;
		}
		return rb;
	}

	/**
	 * 修改对应点位
	 */
	@RequestMapping(value = "updateharewaresite",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject updateharewaresite (String siteid,String filename){
		JSONObject result = new JSONObject();
		SysHardWareData data = new SysHardWareData();
		data.setDataFileName(filename);data.setDataRemark(siteid);
		int i = this.sysHearWordService.updateharewaresite(data);
		result.put("code", "1");
		return result;
	}
}










